import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { communityApi } from "@/api";
import type {
  CommunityShare,
  HelpRequest,
  CreateShareData,
  CreateHelpRequestData,
  ContentFilter,
  InteractionData,
} from "@/types";

export const useCommunityStore = defineStore("community", () => {
  // 状态
  const highlightShares = ref<CommunityShare[]>([]);
  const helpRequests = ref<HelpRequest[]>([]);
  const selectedTags = ref<string[]>([]);
  const popularTags = ref<string[]>([]);
  const loading = ref(false);
  const currentFilter = ref<ContentFilter>({
    sortBy: "newest",
    page: 1,
  });

  // 计算属性
  const filteredShares = computed(() => {
    if (selectedTags.value.length === 0) {
      return highlightShares.value;
    }
    return highlightShares.value.filter((share) =>
      share.tags.some((tag) => selectedTags.value.includes(tag))
    );
  });

  const hasMoreShares = ref(true);
  const hasMoreRequests = ref(true);

  // 方法
  async function fetchHighlightShares(params?: ContentFilter, append = false) {
    try {
      loading.value = true;

      // 只传递API支持的参数
      const apiParams: any = {};
      if (params?.page || currentFilter.value.page) {
        apiParams.page = params?.page || currentFilter.value.page;
      }
      if (params?.category) {
        apiParams.share_type = params.category;
      }

      const response = await communityApi.getShares(apiParams);

      // 处理不同的响应格式
      let sharesData: CommunityShare[] = [];
      if (Array.isArray(response)) {
        sharesData = response;
      } else if (
        response &&
        "data" in response &&
        Array.isArray(response.data)
      ) {
        sharesData = response.data;
      }

      if (append) {
        highlightShares.value.push(...sharesData);
      } else {
        highlightShares.value = sharesData;
      }

      // 简单的分页检查
      hasMoreShares.value = sharesData.length === 20; // 假设每页20条
      currentFilter.value = { ...currentFilter.value, ...params };

      return { data: sharesData };
    } catch (error) {
      console.error("Failed to fetch highlight shares:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  }

  async function fetchHelpRequests(params?: ContentFilter, append = false) {
    try {
      loading.value = true;

      // 只传递API支持的参数
      const apiParams: any = {};
      if (params?.page || currentFilter.value.page) {
        apiParams.page = params?.page || currentFilter.value.page;
      }
      if (params?.status) {
        apiParams.status = params.status;
      }
      if (params?.category) {
        apiParams.category = params.category;
      }

      const response = await communityApi.getHelpRequests(apiParams);

      // 处理不同的响应格式
      let requestsData: HelpRequest[] = [];
      if (Array.isArray(response)) {
        requestsData = response;
      } else if (
        response &&
        "data" in response &&
        Array.isArray(response.data)
      ) {
        requestsData = response.data;
      }

      if (append) {
        helpRequests.value.push(...requestsData);
      } else {
        helpRequests.value = requestsData;
      }

      // 简单的分页检查
      hasMoreRequests.value = requestsData.length === 20; // 假设每页20条

      return { data: requestsData };
    } catch (error) {
      console.error("Failed to fetch help requests:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  }

  async function publishShare(shareData: CreateShareData) {
    try {
      const share = await communityApi.createShare(shareData);
      highlightShares.value.unshift(share);
      return share;
    } catch (error) {
      console.error("Failed to publish share:", error);
      throw error;
    }
  }

  async function publishHelpRequest(requestData: CreateHelpRequestData) {
    try {
      const request = await communityApi.createHelpRequest(requestData);
      helpRequests.value.unshift(request);
      return request;
    } catch (error) {
      console.error("Failed to publish help request:", error);
      throw error;
    }
  }

  async function interactWithShare(shareId: number, data: InteractionData) {
    try {
      await communityApi.interactWithShare(shareId, data);

      // 更新本地状态
      const share = highlightShares.value.find((s) => s.id === shareId);
      if (share) {
        switch (data.type) {
          case "like":
            if (share.isLiked) {
              share.likesCount--;
              share.isLiked = false;
            } else {
              share.likesCount++;
              share.isLiked = true;
              if (share.isDisliked) {
                share.dislikesCount--;
                share.isDisliked = false;
              }
            }
            break;
          case "dislike":
            if (share.isDisliked) {
              share.dislikesCount--;
              share.isDisliked = false;
            } else {
              share.dislikesCount++;
              share.isDisliked = true;
              if (share.isLiked) {
                share.likesCount--;
                share.isLiked = false;
              }
            }
            break;
          case "comment":
            share.commentsCount++;
            break;
        }
      }
    } catch (error) {
      console.error("Failed to interact with share:", error);
      throw error;
    }
  }

  async function fetchPopularTags() {
    try {
      const tags = await communityApi.getPopularTags();
      popularTags.value = tags;
    } catch (error) {
      console.error("Failed to fetch popular tags:", error);
    }
  }

  function updateSelectedTags(tags: string[]) {
    selectedTags.value = tags;
    // 重新获取内容
    fetchHighlightShares({ page: 1 });
  }

  function updateFilter(filter: Partial<ContentFilter>) {
    currentFilter.value = { ...currentFilter.value, ...filter };
    fetchHighlightShares({ page: 1 });
  }

  async function loadMoreShares() {
    if (!hasMoreShares.value || loading.value) return;

    const nextPage = (currentFilter.value.page || 1) + 1;
    await fetchHighlightShares({ page: nextPage }, true);
  }

  async function loadMoreRequests() {
    if (!hasMoreRequests.value || loading.value) return;

    const nextPage = (currentFilter.value.page || 1) + 1;
    await fetchHelpRequests({ page: nextPage }, true);
  }

  function refreshContent() {
    currentFilter.value.page = 1;
    fetchHighlightShares();
    fetchHelpRequests();
  }

  async function togglePostFavorite(postId: number) {
    try {
      // TODO: Call API to toggle post favorite
      // await communityApi.togglePostFavorite(postId)

      // Mock implementation
      const post = highlightShares.value.find((p) => p.id === postId);
      if (post) {
        // Toggle favorite status (this would come from API response)
        post.isFeatured = !post.isFeatured;
      }
    } catch (error) {
      console.error("Failed to toggle post favorite:", error);
      throw error;
    }
  }

  return {
    // 状态
    highlightShares,
    helpRequests,
    selectedTags,
    popularTags,
    loading,
    currentFilter,

    // 计算属性
    filteredShares,
    hasMoreShares,
    hasMoreRequests,

    // 方法
    fetchHighlightShares,
    fetchHelpRequests,
    publishShare,
    publishHelpRequest,
    interactWithShare,
    fetchPopularTags,
    updateSelectedTags,
    updateFilter,
    togglePostFavorite,
    loadMoreShares,
    loadMoreRequests,
    refreshContent,
  };
});
